<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-10-24
 * @Time: 15:08
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： CollectionSinaNewStock.php
 */
namespace app\admin\command;

use QL\QueryList;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * 定时任务
 *
 * @author zhengkai
 *
 * Class CollectionSinaNewStock
 * @package app\admin\command
 */
class CollectionSinaNewStock extends Command {
    /**
     * 新浪新股日历数据采集
     * 命令：php think getNewStock
     */
    protected function configure()
    {
        $this->setName('getNewStock')->setDescription('新浪新股日历数据采集');
    }

    protected function execute(Input $input, Output $output)
    {
        $ql = QueryList::getInstance();

        // 抓取页面字符串数据
        $html = $ql->get('http://vip.stock.finance.sina.com.cn/corp/go.php/vRPD_NewStockIssue/page/1.phtml');
        $html = $html->find('#NewStockTable')->htmls();
        $html = iconv("gb2312", "utf-8//IGNORE", $html[0]);

        // 取得所需数据
        $data = $ql->html($html)->rules([
            'zjdm' => ['td:eq(0)>div', 'text'], // 证券代码
            'sgdm' => ['td:eq(1)>div', 'text'], // 申购代码
            'zjjc' => ['td:eq(2)>div', 'text'], // 证券简称
            'swfxrq' => ['td:eq(3)>div', 'text'], // 上网发行日期
            'fxjg' => ['td:eq(7)>div', 'text'], // 发行价格
        ])->range('tr')->query()->getData();

        // 重新遍历排序后组成新的数据
        $arr = [];
        foreach ($data->all() as $key=>$val) if ($key>2) $arr[] = $val;
        $data = array_sort($arr, 'swfxrq', 'asc');

        // 写入数据库
        foreach ($data as $key=>$val) {
            // echo $val['zjdm'].'|'.$val['sgdm'].'|'.$val['zjjc'].'|'.$val['swfxrq'].'|'.$val['fxjg'].'|'.PHP_EOL;
            $data = [
                'zjdm' => $val['zjdm'], // 证券代码
                'sgdm' => $val['sgdm'], // 申购代码
                'zjjc' => trim($val['zjjc']), // 证券简称
                'swfxrq' => strtotime($val['swfxrq']), // 上网发行日期（申购日期）
                'fxjg' => $val['fxjg'], // 发行价格（申购价格）
                'created' => time() // 数据采集时间
            ];

            if ($this->isExist($val['zjdm'])) {
                echo "证券：{$val['zjjc']}（{$val['zjdm']}）已存在，不需要采集".PHP_EOL;
            } else {
                $insert = Db::table('stock_new')->insert($data);
                if ($insert) {
                    echo "证券：{$val['zjjc']}（{$val['zjdm']}）数据采集成功".PHP_EOL;
                } else {
                    echo "证券：{$val['zjjc']}（{$val['zjdm']}）数据采集失败".PHP_EOL;
                }
            }
        }
    }

    /**
     * isExist
     * 查询数据库中是否已存在重复的股票数据
     *
     * @author zhengkai
     * @data 2017-10-24
     *
     * @param int/string $zjdm 证券代码
     * @return bool
     */
    private function isExist($zjdm)
    {
        $sql = <<<SQL
        select count(id) as total from stock_new where zjdm='{$zjdm}';
SQL;
        $data = Db::query($sql);
        $result = $data[0]['total'];

        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}